package io.phone;

/**
 * @author Patrick van Gils, 0787862, INF3M
 * Various calculcations
 */

public class CoordinateCalculation {
	
	/**
	 * Calcalute the distance between two (decimal) gps coordinates
	 * 
	 * @param lat1
	 * @return Float
	 */
	public float calculateDistance(double lat1, double long1, double lat2, double long2) throws Exception
	{
		double earthRadius = 3958.75;
		
		double dLat = Math.toRadians(lat2-lat1);
		double dLng = Math.toRadians(long2-long1);
		
		double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
		Math.sin(dLng/2) * Math.sin(dLng/2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		double dist = earthRadius * c;
	
		int meterConversion = 1609;
	
		return new Float(dist * meterConversion).floatValue();
	}
	
	/**
	 * Calculate the direction between two (decimal) GPS coordinates
	 * 
	 * @param lat1
	 * @return Float
	 */
	public float calculateDirectionHeading(double lat1, double long1, double lat2, double long2) throws Exception
	{
	    lat1 = Math.toRadians(lat1);
	    long1 = Math.toRadians(long1);
	    lat2 = Math.toRadians(lat2);
	    long2 = Math.toRadians(long2);

	    double bearingradians = Math.atan2(Math.asin(long2-long1)*Math.cos(lat2),Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(long2-long1));
	    double bearingdegrees = Math.toDegrees(bearingradians);
	    if (bearingdegrees < 0)
	    {
	      bearingdegrees = 360 + bearingdegrees;
	    }
	    return (float) bearingdegrees;
	}
}
